/*
 * 文 件 名:  UploadFileAction.java
 * 版    权:   . Copyright YYYY-YYYY,  All rights reserved
 * 描    述:  <描述>
 * 修 改 人:  simon
 * 修改时间:  2011-9-10
 */
package org.simoncook.uploadfile.demo.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

/**
 * <一句话功能简述>
 * <功能详细描述>
 * 
 * @author  chenxiaguang@gmail.com
 * @version  [版本号, 2011-9-10]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class UploadFileAction extends HttpServlet
{

    /**
     * 注释内容
     */
    private static final long serialVersionUID = -515868464924773982L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
    {
        System.out.println("Enter UploadFileAction:doPost");
        SmartUpload upload = new SmartUpload();
        upload.initialize( this.getServletConfig(), req, resp);
        upload.setMaxFileSize(1l*1024*1024*1000);
        try
        {
            upload.upload();
        }
        catch (SmartUploadException e)
        {
            e.printStackTrace();
        }
        int count = upload.getFiles().getCount();
        long currentTime = System.currentTimeMillis();
        Date date = new Date(currentTime);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_hh_mm_ss");
        String currentTimeFlag = sdf.format(date);
        String destFilePathName = "/home/simon/800.temp/test_upload_" + currentTimeFlag;
        for(int i=0; i<count; i++)
        {
            com.jspsmart.upload.File uploadFile = upload.getFiles().getFile(i);
            if(!uploadFile.isMissing())
            {
                try
                {
                    uploadFile.saveAs(destFilePathName);
                }
                catch (SmartUploadException e)
                {
                    e.printStackTrace();
                }
            }
        }

        //用forward的话 F5的问题难解决
        //req.getRequestDispatcher("/").forward(req, resp);
        
        // F5刷新问题用重定向不要用forward就可以解决
        resp.sendRedirect("index.jsp?uploadRes=success");
        
    }

}
